#include "httpmgr.h"
#include<QThread>
HttpMgr::~HttpMgr()
{

}

HttpMgr::HttpMgr() {
    // _manager=new QNetworkAccessManager(this);
    //连接http请求和完成信号，信号槽机制保证队列消费
    connect(this,&HttpMgr::sig_http_finish,this,&HttpMgr::slot_http_finish);
}

void HttpMgr::PostHttpReq(QUrl url, QJsonObject json, ReqId req_id, Modules mod)
{
    QNetworkAccessManager* _manager= new QNetworkAccessManager;

    //转化为网络字节
    QByteArray data=QJsonDocument(json).toJson();

    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,data.length());
    //发送请求，并接受响应
    auto self=shared_from_this();
    QNetworkReply *reply=_manager->post(request,data);

    //设置信号和槽等待发送完毕
    QObject::connect(reply,&QNetworkReply::finished,[reply,self,req_id,mod](){
        //处理错误情况
        if(reply->error()!=QNetworkReply::NoError){
            qDebug()<<"reply is: "<<reply->errorString();

            //发送消息通知完成
            emit self->sig_http_finish(req_id,"",ErrorCodes::ERR_NETWORK,mod);
            reply->deleteLater();
            return;
        }
        //无错误则读回请求
        QString res=reply->readAll();
        emit self->sig_http_finish(req_id,res,ErrorCodes::SUCCESS,mod);
        reply->deleteLater();

        return;
    });
}

void HttpMgr::GetHttpReq(QUrl url,ReqId req_id, Modules mod)
{
    QNetworkAccessManager* _manager= new QNetworkAccessManager;

    QNetworkRequest request;          //定义一个请求对象
    request.setUrl(url);
    auto self=shared_from_this();
    QNetworkReply* reply=_manager->get(request);
    QObject::connect(reply,&QNetworkReply::finished,[_manager,reply,self,req_id,mod](){
        //处理错误情况
        if(reply->error()!=QNetworkReply::NoError){
            qDebug()<<"reply is: "<<reply->errorString();
            //发送消息通知完成
            emit self->sig_http_finish(req_id,"",ErrorCodes::ERR_NETWORK,mod);
            reply->deleteLater();
            return;
        }
        //无错误则读回请求

        QString res=reply->readAll();
        qDebug()<<"http get success!";
        emit self->sig_http_finish(req_id,res,ErrorCodes::SUCCESS,mod);
        reply->deleteLater();
        _manager->deleteLater();
    });


}

void HttpMgr::slot_http_finish(ReqId id, QString res, ErrorCodes err, Modules mod)
{
    if(mod==Modules::SEARCHMUSICMODE){
        //发送通知到指定模块http响应结束
        qDebug()<<"emit sig_search_mod_finish";
        emit sig_search_mod_finish(id,res,err);
    }

}
